<template>
  <div class="main-content-box">
    <div id="topoDemo">
      <!-- <div class="toolDiv">
        <el-button type="success" icon="el-icon-check" circle @click="saveGraphData"></el-button>
      </div>-->
      <div id="container"></div>

      <!-- <div class="tool_area">
        <el-select
          v-model="anchorSelectValue"
          placeholder="请选择"
          style="float:right;margin-top:4px;margin-right: 10px;"
          @change="changeAnchorList"
        >
          <el-option
            v-for="item in anchorOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>-->
    </div>
  </div>
</template>

<script>
import G6 from '@antv/g6';
import { fetchAnchorPoints } from '../../../nodeApi/api/getData.js'
import echarts from 'echarts'

export default {
  name: 'changeAnchorPoints',
  data () {
    return {
      orgData: {},
      currentGraph: null,
      anchorOptions: [
        {
          value: `defaultAnchor`,
          label: '锚点数：4',
          id: 1
        }, {
          value: `middleAnchor`,
          label: '锚点数：8',
          id: 2
        }, {
          value: `largeAnchor`,
          label: '锚点数：16',
          id: 3
        }
      ],
      anchorSelectValue: ''
    }
  },
  created () {
    fetchAnchorPoints().then(res => {
      console.log(res)
      if (res.status === 0) {
        this.orgData = res.data
      }
      setTimeout(() => {
        this.getInit()
        this.$nextTick(() => {
          this.initCharts()
          // this.forCharts()
        })
      }, 10);
    })
  },
  mounted () {

  },
  methods: {
    getInit () {
      let _that = this
      /**
       * 目的实现：控制节点的锚点显示数目
       * 自定义节点，在自定义节点中绘制锚点，以数据中的初始锚点数据为依据，进行绘制
       * 下拉选在锚点数目时，修改节点数据中的锚点数据
       * 更新节点
       * ？？？可行性待验证
       */
      // G6.registerNode('def-node', {
      //   options: {
      //     style: {
      //       fill: '#f9f9f9',
      //       stroke: '#bbb',
      //       cursor: 'default',
      //     },
      //     stateStyles: {
      //       selected: {
      //         fill: '#eee',
      //       },
      //       hover: {
      //         cursor: 'pointer',
      //       }
      //     }
      //   },
      //   /**
      //    * 绘制锚点
      //    */
      //   // draw (cfg, group) {
      //   //   const { anchorPoints, width, height, id } = cfg
      //   //   const shape = group.getFirst()
      //   //   if (anchorPoints && anchorPoints.length) {
      //   //     for (let i = 0, len = anchorPoints.length; i < len; i++) {
      //   //       let anchorX
      //   //       let anchorY
      //   //       /* if (shape && shape.getModel().type === 'path') {
      //   //         const point = shape.getLinkPointByAnchor(i / len)
      //   //         anchorX = point.x
      //   //         anchorY = point.y
      //   //       } else {
      //   //         const [x, y] = anchorPoints[i]
      //   //         // 计算Marker中心点坐标
      //   //         const originX = -width / 2
      //   //         const originY = -height / 2
      //   //         anchorX = x * width + originX
      //   //         anchorY = y * height + originY
      //   //       } */
      //   //       const [x, y] = anchorPoints[i]
      //   //       // 计算Marker中心点坐标
      //   //       const originX = -width / 2
      //   //       const originY = -height / 2
      //   //       anchorX = x * width + originX
      //   //       anchorY = y * height + originY
      //   //       /**
      //   //        * 添加锚点marker 形状
      //   //        */
      //   //       const anchorShape = group.addShape('marker', {
      //   //         id: id + '_anchor_ponit' + i,
      //   //         name: 'anchorPoint',
      //   //         attr: {
      //   //           boxName: 'anchor',
      //   //           name: 'anchorPoint',
      //   //           x: anchorX,
      //   //           y: anchorY,
      //   //           // 锚点默认样式
      //   //           style: {
      //   //             r: 3,
      //   //             symbol: 'circle',
      //   //             fill: '#FFFFFF',
      //   //             fillOpacity: 0,
      //   //             stroke: '#1890FF',
      //   //             strokeOpacity: 0,
      //   //             cursor: 'crosshair'
      //   //           }
      //   //         }
      //   //       })



      //   //     }
      //   //   }

      //   // }
      // }, 'rect')

      G6.registerNode('dom-node', {
        draw: (cfg, group) => {
          const stroke = cfg.style ? cfg.style.stroke || '#5B8FF9' : '#5B8FF9';
          const shape = group.addShape('dom', {
            name: 'dom-' + cfg.id,
            attrs: {
              width: 500,
              height: 300,
              html: `
        <div id=${cfg.id} class='dom-node' style="background-color: #fff; border: 2px solid ${stroke}; border-radius: 5px; width: ${cfg.size[0] + 50}px; height: ${cfg.size[1] + 50}px; display: flex;">
          <div style="height: 100%; width: 33%; background-color: #CDDDFD">
            <img alt="" style="line-height: 100%; margin-left: 7px;" src="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ" width="20" height="20" />  
          </div>
          <span style="margin:auto; padding:auto; color: #5B8FF9">${cfg.label}</span>
        </div>
          `
            },
            draggable: true
          });
          return shape;
        }
      });
      G6.registerNode('dom-node2', {
        draw: (cfg, group) => {
          const stroke = cfg.style ? cfg.style.stroke || '#5B8FF9' : '#5B8FF9';
          const shape = group.addShape('dom', {
            name: 'dom-' + cfg.id,
            attrs: {
              width: cfg.size[0],
              height: cfg.size[1],
              html: `
              <div style="pading:5px;background-color:#999999;">             
                <div onclick="console.log('Hi')" ref=${cfg.id} id="${cfg.id}" class='dom-node' style="background-color: #fff; border: 2px solid ${stroke}; border-radius: 5px; width: ${cfg.size[0] - 5}px; height: ${cfg.size[1] - 5}px; "></div>
              </div>        
          `
            },
            draggable: true
          });
          return shape;
        }
      });

      /** 数据 */
      const data = {
        nodes: [
          {
            id: 'node0',
            x: 10,
            y: 100,
            label: 'Homepage',
          },
          {
            id: 'node1',
            x: 400,
            y: 100,
            label: 'Subpage',
          },
        ],
        edges: [
          {
            source: 'node1',
            target: 'node2',
          },
        ],
      };

      const width = document.getElementById('container').scrollWidth;
      const height = document.getElementById('container').scrollHeight || 500;
      const graph = new G6.Graph({
        container: 'container',
        width,
        height,
        modes: {
          // default: ['drag-canvas', 'drag-node'],
          default: ['drag-canvas', 'zoom-canvas'],
        },
        // translate the graph to align the canvas's center, support by v3.5.1
        fitCenter: true,
        renderer: 'svg',
        linkCenter: true,
        defaultNode: {
          type: 'dom-node',
          // type: 'dom-node2',
          size: [400, 90]
        }
      });

      // graph.data(data);
      graph.data(_that.orgData);
      graph.render();

      let gNode = graph.findAll('node', node => {
        console.log(node)
        // let nodeContent = node.getBBox()
        // console.log(nodeContent)
        // let nodeContent1 = node.getContainer()
        // console.log(nodeContent1)
        return node
      });
      console.log(gNode)
      gNode.forEach((item, index) => {
        let iContent = item.getContainer()
        console.log(iContent)
        // let queryIdStr = 'node' + index
        // console.log(queryIdStr)
        // let domExit = document.getElementById(queryIdStr)
        // let myChart = echarts.init(domExit);
        // let option = this.orgData.nodes[index].chartsOption
        // myChart.setOption(option);
      })
      // click listener for dom nodes to response the click by changing stroke color
      // const listener = (dom) => {
      //   const nodeId = dom.id;
      //   const node = graph.findById(nodeId);
      //   let stroke = '';
      //   if (!node.hasState('selected')) {
      //     stroke = '#f00';
      //     // graph.setItemState(node, 'selected', true);
      //     graph.refresh()
      //     graph.paint()
      //   } else {
      //     stroke = '#5B8FF9';
      //     // graph.setItemState(node, 'selected', false);
      //     graph.refresh()
      //     graph.paint()
      //   }
      //   /* graph.updateItem(nodeId, {
      //     style: {
      //       stroke
      //     }
      //   }); */
      //   graph.refresh()
      //   graph.paint()
      // }

      const bindClickListener = () => {
        const domNodes = document.getElementsByClassName('dom-node')
        console.log(domNodes)
        console.log(typeof domNodes)
        /* for (let i = 0; i < domNodes.length; i++) {
          const dom = domNodes[i];
          dom.addEventListener('click', (e) => {
            listener(dom);
          });
        } */
      }


      bindClickListener();

      /*  graph.on('afterupdateitem', e => {
         bindClickListener();
       }); */

      _that.currentGraph = graph

    },
    saveGraphData () {
      let saveData = this.currentGraph.save()
      console.log(saveData)
      console.log(saveData.nodes)
    },
    /**
     * 改变锚点数
     */
    changeAnchorList () {
      let defaultAnchorArray = [
        [0.5, 0], // top
        [0, 0.5], // left
        [0.5, 1], // bottom
        [1, 0.5], // right
      ]
      let middleAnchorArray = [
        [0, 0],
        [0.5, 0],
        [1, 0],
        [1, 0.5],
        [1, 1],
        [0.5, 1],
        [0, 1],
        [0, 0.5],
      ]
      let largeAnchorArray = [
        [0, 0],
        [0.25, 0],
        [0.5, 0],
        [0.75, 0],
        [1, 0],
        [1, 0.25],
        [1, 0.5],
        [1, 0.75],
        [1, 1],
        [0.75, 1],
        [0.5, 1],
        [0.25, 1],
        [0, 1],
        [0, 0.75],
        [0, 0.5],
        [0, 0.25]
      ]
      let graphNodes = this.currentGraph.getNodes()
      console.log(graphNodes)
      graphNodes.forEach(item => {
        let anchorList = item.getAnchorPoints()
        console.log(anchorList)
        // if (anchorList.length) {
        //   anchorList.length = 0
        //   anchorList = anchorList.concat(middleAnchorArray)
        // }
        // // console.log(anchorList.concat(middleAnchorArray))
        // console.log(anchorList)
        console.log(item)
        console.log(item._cfg.model)
        let nodeTemp = item._cfg.model
        nodeTemp.anchorPoints = middleAnchorArray
        console.log(nodeTemp)
        this.currentGraph.updateItem(item, nodeTemp)
        this.currentGraph.refresh()
      })

    },
    initCharts () {
      // console.log(echarts)
      let forLength = this.orgData.nodes.length
      for (let i = 0; i < forLength; i++) {
        let queryIdStr = 'node' + i
        // console.log(queryIdStr)
        let domExit = document.getElementById(queryIdStr)
        console.log(typeof domExit)
        // console.log(domExit)
        let myChart = echarts.init(domExit);
        // 指定图表的配置项和数据
        let option = this.orgData.nodes[i].chartsOption

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      }
    },
    forCharts () {
      let domExit = document.getElementsByClassName('dom-node')
      console.log(domExit)
      console.log(typeof domExit)
      console.log(domExit.length)
      for (let i of domExit) {
        let myChart = echarts.init(domExit[i], null, { renderer: 'svg' });
        // 指定图表的配置项和数据
        let option = {
          xAxis: {
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
          },
          yAxis: {},
          series: [{
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
          }]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      }
    }
  },
  beforeUpdate () {
    console.log('wahaha')

  }


}

</script>

<style scoped>
.main-content-box {
  width: 95%;
  margin: 5px 20px;
}
.demoDiv {
  position: relative;
  padding: 20px;
  border: 1px solid skyblue;
}
.toolDiv {
  width: 50px;
  border: 1px solid #f5f5f5;
  position: absolute;
  z-index: 100;
}
.tool_area {
  position: absolute;
  top: 0;
  right: 0;
}
</style>